package com.lyw.home

import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.lu.library.base.BaseFragment
import com.lyw.home.databinding.FragmentHomeBinding
import com.lyw.home.databinding.FragmentQuestionBinding
import dagger.hilt.android.AndroidEntryPoint
import me.shouheng.utils.ktx.onDebouncedClick

@Route(path = HomeRouterPaths.HOME_MAIN)
@AndroidEntryPoint
class QuestionFragment : BaseFragment<FragmentQuestionBinding>() {

    private val homeVm by viewModels<QuestionVm>()
    private lateinit var questionAdapter: QuestionAdapter

    override fun initListener() {
        super.initListener()
        binding.clSearch.onDebouncedClick {
            // 搜索按钮点击事件
        }
    }

    override fun initData() {
        binding.setVariable(BR.vm, homeVm)
        setupViewPager()
        homeVm.initDb(requireContext())
    }

    private fun setupViewPager() {
        questionAdapter = QuestionAdapter(homeVm.questions.value ?: emptyList(), homeVm)
        binding.viewPager.adapter = questionAdapter
        binding.viewPager.orientation = ViewPager2.ORIENTATION_HORIZONTAL

        homeVm.questions.observe(viewLifecycleOwner) { questions ->
//            questionAdapter.updateData(questions)
            questionAdapter.addAll(questions)
//            homeVm.currentQuestion.value = questions.getOrNull(homeVm.index.value!!)
        }
        homeVm.itemChanged.observe(viewLifecycleOwner){
            questionAdapter.notifyItemChanged(it)
        }
//        homeVm.index.observe(viewLifecycleOwner) { index ->
//            binding.viewPager.currentItem = index
//        }

        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
//                homeVm._index.value = position
//                homeVm._currentQuestion.value = homeVm.poetries.value?.getOrNull(position)
            }
        })
    }

    override fun layoutResId(): Int = R.layout.fragment_home
}